package org.fast.develop.logicflow.builder;

import cn.hutool.core.util.StrUtil;
import org.fast.develop.logicflow.builder.exception.LogicFlowBuilderExecption;
import org.fast.develop.logicflow.core.meta.shape.LogicFlowDefinition;
import org.fast.develop.logicflow.core.meta.condition.ConditionExpression;
import org.fast.develop.logicflow.core.meta.base.Resource;
import org.fast.develop.logicflow.core.meta.shape.line.SequenceFlow;
import org.fast.develop.logicflow.core.LogicFlowConfiguration;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author 莫寅
 * @createTime 2022-11-27 17:58
 * @desc：
 */
public abstract class AbstractLogicFlowNodeBuilder<T extends AbstractLogicFlowBuilder<T, E>, E extends Resource> extends AbstractLogicFlowBuilder<T, E> {


    private static Queue<SequenceFlow> queue = new LinkedBlockingQueue<>(1);


    public AbstractLogicFlowNodeBuilder(LogicFlowDefinition logicFlowDefinition, LogicFlowConfiguration logicFlowConfiguration) {
        super(logicFlowDefinition, logicFlowConfiguration);
    }


    public T condition(String name, String condition){
        if(queue.size() > 0){
            throw new LogicFlowBuilderExecption(StrUtil.format("当前ifelse控制器：{} ， 已设置条件，不能重复设置：name：{}， condition：{}", this, name, condition));
        }

        SequenceFlow sequenceFlow = getLogicFlowConfiguration().getLogicFlowBuilderFactory().createSequenceFlow();
        ConditionExpression conditionExpression = new ConditionExpression();
        conditionExpression.setExpression(condition);
        sequenceFlow.setCondition(conditionExpression);
        sequenceFlow.setName(name);

        queue.add(sequenceFlow);
        return (T) this;
    }

    /**
     * 增加默认流的条件设置
     * @param name
     * @return
     */
    public T condition(String name){
        if(queue.size() > 0){
            throw new LogicFlowBuilderExecption(StrUtil.format("当前ifelse控制器：{} ， 已设置条件，不能重复设置：name：{}", this, name));
        }

        SequenceFlow sequenceFlow = getLogicFlowConfiguration().getLogicFlowBuilderFactory().createSequenceFlow();
        ConditionExpression conditionExpression = new ConditionExpression();
        conditionExpression.setExpression("${1 == 2}");
        sequenceFlow.setCondition(conditionExpression);
        sequenceFlow.setName(name);
        sequenceFlow.setDefault(true);

        queue.add(sequenceFlow);
        return (T) this;
    }


    public SequenceFlow nextSequenceFlow() {
        return queue.poll();
    }
}
